package handlers

import (
	"encoding/json"
	"net/http"

	"zwai-app/services"
	"zwai-app/util"
)

// 解析前端传过来的手机号
type reqPhone struct {
	Phone string `json:"phone"`
	From  string `json:"from"`
}

// RegisterSMSRoutes 注册短信验证码相关路由
func RegisterSMSRoutes(mux *http.ServeMux) {
	mux.HandleFunc("/sms/sendcode", sendSMSCodeHandler)
}

// sendSMSCodeHandler 处理 POST /sms/sendcode
func sendSMSCodeHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		util.JSONResponse(w, http.StatusMethodNotAllowed, map[string]interface{}{"code": 1, "msg": "只支持 POST 方法"})
		return
	}

	var req reqPhone
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"code": 2, "msg": "参数解析失败"})
		return
	}
	if req.Phone == "" {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"code": 3, "msg": "手机号不能为空"})
		return
	}
	if req.From == "" {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{"code": 4, "msg": "来源不能为空"})
		return
	}
	// 调用你封装的火山引擎短信服务
	smsCode, err := services.SendVolcengineSMSCode(req.Phone, req.From)
	if err != nil {
		codeToReturn := smsCode
		if codeToReturn == "" {
			codeToReturn = "5"
		}
		// smsCode 里可能是 ""（SDK/限频错误）或 CR:xxxx（平台业务错误）
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{
			"code": codeToReturn, // CR:0202、RE:0004 等
			"msg":  "发送失败：" + err.Error(),
		})
		return
	}
	util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 0, "msg": "验证码已发送"})
}
